package com.zjw.concurrency.interview;

/**
 * java创建十个线程模拟抢票
 * */
public class TicketSystem {
    private int tickets = 100; // 总票数
    private final Object lock = new Object(); // 锁对象

    public static void main(String[] args) {
        TicketSystem ticketSystem = new TicketSystem();
        // 创建10个线程模拟抢票
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> ticketSystem.sellTicket(), "用户" + i).start();
        }
    }

    private void sellTicket() {
        while (true) {
            synchronized (lock) {
                if (tickets <= 0) break; // 票已售罄
                System.out.println(Thread.currentThread().getName() + " 抢到第 " + tickets-- + " 张票");
            }
            try {
                Thread.sleep(100); // 模拟抢票延迟
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
